<?php
namespace app\index\controller;

use app\common\utils\ResultVOUtil;
use Firebase\JWT\JWT;
use app\common\enums\ResultEnum;
use app\common\exception\ZeduException;
use think\facade\Log;
use think\facade\Config;
use think\Controller;
use think\Db;
use think\Validate;
use app\common\model\AdminRole;
use app\common\model\AccessRole;
use app\common\model\AccessMenu;
use app\common\model\AccessElement;
use app\common\model\Element;
use app\common\model\Admin;
use think\Request;
use app\common\request\Curl;

class Login extends Controller
{
    
    public function index($jwt='') {
        if($jwt!==''){
            $key = md5('abcdefghijklmn123456789');
            $decoded = JWT::decode($jwt, $key, array('HS256'));
            if($decoded){
                $id = $decoded->id;
                $model =  Admin::where(['id'=>$id])->field('id,agency_id,password,nick_name,role_id,last_login,last_ip,status,user_name')->find();
                
                $data = [];
                $data = $this->storage($model);
                $data['access'] = $this->access($model['id']);
                $data['agency_id'] = $this->agency($model);
                session('admin',$data);          
            
                $data['token'] = md5(time());
                $data['address'] = $this->address($model['last_ip']);
               
                return ResultVOUtil::success($data);
            }else{
                throw new ZeduException(['code'=>ResultEnum::LOGIN_FAIL['code'],'msg'=>'登录失败']);
            }
        }
    }
    
    public function login(Request $request,$user_name='',$password=''){
        if($user_name!=='' && $password!==''){
                $data = [];
                $data['user_name'] = $user_name;
                $data['password'] = $password;
                $rule = [
                    'user_name'  => 'require|number',
                    'password' => 'require'
                ];
                $msg = [
                    'user_name.require' => '账号必须',
                    'user_name.number'     => '账号必须是数字',
                    'password.require' => '密码必须'
                ];
                $validate = Validate::make($rule)->message($msg);
                $result = $validate->check($data);
                
                if(!$result){
                    return ResultVOUtil::error(ResultEnum::LOGIN_FAIL['code'],$validate->getError());
                }
                
                try{
                    $admin = Admin::where('user_name',$user_name)->field('id,agency_id,password,nick_name,role_id,last_login,last_ip,status,user_name')->find();

                    
                }catch(\Exception $e){
                    Log::record('user_name查询admin表'.$e->getMessage());
                    return ResultVOUtil::error(ResultEnum::LOGIN_FAIL);
                }
                if($admin == null){
                    return ResultVOUtil::error(ResultEnum::LOGIN_FAIL['code'],'用户名不存在');
                }

                if($admin['status'] != 1){
                    return ResultVOUtil::error(ResultEnum::LOGIN_FAIL['code'],'用户被禁用');
                }
                if(!password_verify($password,$admin['password'])){
                    return ResultVOUtil::error(ResultEnum::LOGIN_FAIL['code'],'密码不正确');
                }

                try {
                    Db::name('admin')->update(['last_ip'=>$request->ip(),'last_login'=>time(),'id'=>$admin['id']]);
                } catch (\Exception $e) {
                    Log::record('[admin表更新ip]:' . $e->getMessage(), 'error');
                    return ResultVOUtil::error(ResultEnum::UPDATE_ERROR);
                }
                
                $login = [];
                $login['id'] = $admin['id'];
                $login['nick_name'] = $admin['nick_name'];
                $login['last_login'] = $admin['last_login'];
                $login['user_name'] = $admin['user_name'];
                $login['access'] = $this->access($admin['id']);
                $login['agency_id'] = $this->agency($admin);
                session('admin',$login);
                $login['address'] = $this->address($admin['last_ip']);
                
                return ResultVOUtil::success($login);
            
        }else{
            throw new ZeduException(ResultEnum::PARAM_ERROR);
        }
    }
    
    private function storage($data){
        $login = [];
        $login['id'] = $data['id'];
        $login['nick_name'] = $data['nick_name'];
        $login['last_login'] = $data['last_login'];
        $login['user_name'] = $data['user_name'];
        return $login;
    } 
    
    private function access($id){
        $role_id = AdminRole::where(['admin_id'=>$id])->column('role_id');
        $access_id = AccessRole::where('role_id','in',$role_id)->column('access_id');
        $data = [];
        $data['menu'] = $this->menu($access_id);
        $data['element'] = $this->element($access_id);
        return $data;
    }
    
    private function menu($access_id){
        $menu = AccessMenu::with('menu')->where('access_id','in',$access_id)->select();
        $datum = [];
        if(!empty($menu)){
            foreach ($menu as  $value){
                if(!empty($value['menu'][0])){
                    $datum[] = $value['menu'][0]['url'];
                }
            }
        }
        return $datum;
    }
    
    private function element($access_id){
       $element_id = AccessElement::where('access_id','in',$access_id)->column('element_id');
        $element = Element::where('id','in',$element_id)->select();
        $datum = [];
        if(!empty($element)){
            foreach ($element as $value){
                $datum[$value['page']][] = $value['name'];
            } 
        }
        return $datum; 
    }
    
    private function agency($admin){
        $agencyData = $admin->agency;    
        $data = '';
        foreach ($agencyData as $key => $value){
            if($key!=0){
                $data .= ',';
            }
            $data .= $value['path'];
        }
        return $data; 
    }
     
    public function address($ip){
        $key = Config::get('gaode.key');
        $host = "https://restapi.amap.com";
        $path = "/v3/ip";
        $url = $host . $path . "?" . "ip=" . $ip . "&output=json" . "&key=" . $key;
        $curl = new Curl;
        $curl->url($url);
        
        if ($curl->error()) {
            Log::record('[ip查询地址]'.$curl->message(),'error');
            return ResultVOUtil::error(ResultEnum::ERROR);
        } else {
            
            $info = $curl->info();
            if($info['http_code'] == 200){
                
                $content = $curl->data();
                
            }
            
            if($content){
                $arr = json_decode($content,true);
                return $arr;
            }
            
        }     
    }
    

}

